
import * as vscode from 'vscode';
import { HtmlBuilder } from './ui/HtmlBuilder';
import { AgentController } from '../controller/AgentController';
import { IAgentView } from './IAgentView';
import { TestAgentBus } from '../bus/TestAgentBus';
import { ToolResult } from '../types/types';
import { ToolDefinition } from '../types/types';
import { Attachment } from '../types/types';
import { Message,ManualToolHistoryItem} from '../types/types';

/**
 * 实现了IAgentView接口，作为TestAgent的ui与controller交互的桥梁
 */
export class TestAgentView implements vscode.WebviewViewProvider,IAgentView {

    public static readonly viewType = 'testAgentGUIView'; // Webview 的唯一标识符

    private _view?: vscode.WebviewView; // 当前 Webview 实例

    private _htmlBuilder:HtmlBuilder; // 构建html内容

    private _controller:AgentController; // agent 控制器，移交前端请求

    private _messager:TestAgentBus; // 消息总线，负责前后端通信

    
     constructor(
            private readonly _extensionUri: vscode.Uri,
            private readonly _context: vscode.ExtensionContext
            
        ) {
            this._htmlBuilder = new HtmlBuilder(this._extensionUri);
            this._messager = new TestAgentBus(); // 初始化消息总线
            this._controller = new AgentController(this._context, this._messager,this); // 绑定控制器处理的视图和消息总线
        }



        /**
        * 解析并设置 Webview 视图的内容
        * @param webviewView Webview 视图实例
        * @param context Webview 解析上下文
        * @param token 取消令牌
        */
       resolveWebviewView(webviewView: vscode.WebviewView,
                          context: vscode.WebviewViewResolveContext, 
                          token: vscode.CancellationToken
       ): Thenable<void> | void {

                this._view = webviewView; // 保存 Webview 实例
                
                // 设置 Webview 选项
                webviewView.webview.options = {
                    enableScripts: true, // 启用脚本
                    localResourceRoots: [ // 设置本地资源根路径
                        vscode.Uri.joinPath(this._extensionUri, 'media'),
                        vscode.Uri.joinPath(this._extensionUri, 'node_modules')
                    ]
                };
        
                // 设置 Webview 的 HTML 内容
                webviewView.webview.html = this._htmlBuilder.getHtml(webviewView.webview);

                // 注册消息总线
                this._messager.registerWebview(webviewView.webview,[]);
                
                // 🟢 监听 webview 销毁事件,清理资源
                webviewView.onDidDispose(() => {
                    console.log('[TestAgentView] Webview disposed, cleaning up resources');
                    this._controller.dispose();
                });
                
                // 3. 通知 Controller 视图已就绪，进行数据初始化
                setTimeout(() => {
                    this._controller.onViewReady();
                }, 100);
       }

// ==========================================
// IAgentView 接口实现
// ==========================================

    public async showErrorMessage(text: string): Promise<void> {
        await this._messager.sendMessage({ type: 'error', text });
    }

    public async notifyChatCleared(): Promise<void> {
        await this._messager.sendMessage({ type: 'clearSuccess' });
    }

    public async showAssistantResponse(text: string): Promise<void> {
        await this._messager.sendMessage({ type: 'response', text });
    }

    public async streamAssistantResponse(messageId: string, chunk: string): Promise<void> {
        await this._messager.sendMessage({ type: 'streamChunk', messageId, chunk });
    }

    public async clearStreamMessage(messageId: string): Promise<void> {
        await this._messager.sendMessage({ type: 'clearStreamMessage', messageId });
    }

    public async updateToolList(tools: ToolDefinition[]): Promise<void> {
        await this._messager.sendMessage({ type: 'toolList', tools });
    }

    public async showToolResult(result: ToolResult): Promise<void> {
        await this._messager.sendMessage({ type: 'toolResult', result });
    }

    public async requestToolConfirmation(toolCall: any, messageId: string): Promise<void> {
        await this._messager.sendMessage({ type: 'toolConfirmation', toolCall, messageId });
    }

    public async notifyFilesSelected(files: Attachment[]): Promise<void> {
        await this._messager.sendMessage({ type: 'filesSelected', files });
    }

    public async restoreHistory(messages: Message[]): Promise<void> {
        await this._messager.sendMessage({ type: 'restoreHistory', messages });
    }

    public async restoreManualHistory(history: ManualToolHistoryItem[]): Promise<void> {
        await this._messager.sendMessage({ type: 'restoreManualHistory', history });
    }
}